#[macro_use] extern crate nickel;
extern crate rustc_serialize;

use nickel::Nickel;
use nickel::HttpRouter;

use rustc_serialize::json::Json;
use rustc_serialize::json::ToJson;

mod student;
use student::Student;

use std::collections::BTreeMap;

#[macro_use]
extern crate mysql;
use mysql::value::from_value;
use mysql as my;

#[derive(Debug, PartialEq, Eq)]
struct Result {
    from: String,
    list: Vec<Student>
}

impl ToJson for Result {
    fn to_json(&self) -> Json {
        let mut data = BTreeMap::new();
        data.insert("from".to_string(), self.from.to_json());
        data.insert("list".to_string(), self.list.to_json());
        Json::Object(data)
    }
}

fn main() {
    let mut server = Nickel::new();
    server.get("/mysql", middleware!{
        let pool = my::Pool::new("mysql://root:linux2016@localhost").unwrap();
        let students: Vec<Student> = pool.prep_exec("SELECT username, phone, grade, school from linux.mock", ())
        .map(|result| {
            result.map(|x| x.unwrap()).map(|row| {
                let (username, phone, grade, school) = my::from_row(row);
                Student::new(username, phone, grade, school)
            }).collect()
        }).unwrap();
        let source = String::from("rust");
        let res = Result {from: source, list: students};
        res.to_json()
    });

    server.listen("127.0.0.1:3004");
}
